package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

func getStock() {
	stocks := openStock()

	filePtr, err := os.OpenFile("./库存", os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println("文件打开失败 [Err:%s]", err.Error())
	}
	defer filePtr.Close()
	//写入文件时，使用带缓存的 *Writer
	write := bufio.NewWriter(filePtr)
	for i := 0; i < len(stocks); i++ {
		atoi, _ := strconv.Atoi(stocks[i])
		write.WriteString(strconv.Itoa(atoi / 2))
		write.WriteString("\n")
	}
	//Flush将缓存的文件真正写入到文件中
	write.Flush()

}

func openStock() []string {
	filePtr, err := os.Open("./销量")
	if err != nil {
		fmt.Println("文件打开失败 [Err:%s]", err.Error())
	}
	defer filePtr.Close()

	var lines []string
	reader := bufio.NewReader(filePtr)
	for {
		line, err := reader.ReadString('\n')
		if err == io.EOF {
			lines = append(lines, line)
			break
		}
		if err != nil {
			return lines
		}
		lines = append(lines, line[:len(line)-2])
	}
	return lines
}
